package com.dmall.search.message;

import com.dmall.manager.model.ItemModel;
import com.dmall.manager.service.ItemService;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * 监听商品添加消息，接受消息后将对应的商品信息同步到索引库
 * @author Chen 2017/11/1
 */
public class ItemAddMessageListener implements MessageListener {

    @Autowired
    private ItemService itemService;
    @Autowired
    private SolrServer solrServer;


    @Override
    public void onMessage(Message message) {
        try {

            String text = null;
            TextMessage textMessage = (TextMessage) message;
            text = textMessage.getText();
            Long itemId = new Long(text);
            ItemModel searchItem = itemService.getItemModelById(itemId);
            //创建一个文档对象
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id",searchItem.getId());
            document.addField("item_title",searchItem.getTitle());
            document.addField("item_sell_point",searchItem.getSell_point());
            document.addField("item_image",searchItem.getImage());
            document.addField("item_price",searchItem.getPrice());
            document.addField("item_category_name",searchItem.getCategory_name());
            //把文档写入索引库
            solrServer.add(document);
            solrServer.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
